/*Star rating UI component*/
/*
 * container:   JQuery Object, the container for star rating
 * profile:     JSON, {total:5,score:0...}
 * callbacks:   Object, {onClick, return the score}
 * 
 * getScore:    Function, get the score
 * setScore:    Function, set the score
 */
if (!Util){
    var Util = {};
}
Util.star=function(container,profile,callbacks){
	this.HTML='<span class="qs-ui-ratingstar"></span>';
    this.el=null;
	this.container=container;
	this.stars=[];
	this.profile={
		total:5,
		score:0
	};
	if(profile) {
        $.extend(this.profile,profile);
    }
    this.callbacks=callbacks||{}; 	
	this.init();
};
Util.star.prototype={
	init:function(){
		this.el=$(this.HTML);
		this.container.append(this.el);
		//creat stars according to total (default 5)
        //the default state of star is unselectd
        //select stars according to score
		var total=this.profile.total;
		var score=this.profile.score>total?total:this.profile.score;		
		var state='';
		for(var i=0;i<total;i++){
			state=i<score?'slt':'';
			this._createStar(i,state);
		}
	},
	_createStar:function(i,state){
		var self=this;		
		var star={};
		star.id=i+1;
		star.dom=$('<a href="#" class="'+state+'"></a>').appendTo(this.el);
		this.stars[i]=star;
		star.dom.unbind('star');
		star.dom.bind('click.star',function(e){
			e.preventDefault();
			self._renderStar(star.id,'slt');			
			if(typeof(self.callbacks.onClick)== "function"){
	            self.callbacks.onClick(self.profile.score);
	        }
		});
		star.dom.bind('mouseover.star',function(e){
            self._renderStar(star.id,'hover');         
        });
		star.dom.bind('mouseout.star',function(e){
			self._renderStar(0,'hover');
        });
	},
    reset:function(){
        this._renderStar(0,'slt');
    },
	_renderStar:function(id,cls){
		var k=id;//current star' id
		var t=this.stars.length;//total number of stars
		for(var i=0;i<k;i++){
			this.stars[i].dom.addClass(cls);            
		}
		for(var i=k;i<t;i++){
			this.stars[i].dom.removeClass(cls);
		}
		if(cls=='slt'){this.profile.score=id;}
	},
	getScore:function(){
		return this.profile.score;
	},
	setScore:function(score){
		var score=score>this.profile.total?this.profile.total:score;
		this._renderStar(score,'slt');
	}
};